RedDemandante = function(){
	var index = 0;
	return {
		confirmProcess: function(grid, rowIndex, currentId){
			Asg.Message.confirm(Asg.constants.CONFIRM_DELETE_MESSAGE, function(btn){
				if(btn != "no") RedDemandante.deleteDetails(grid, rowIndex, currentId);
			});
		},
		selectionChange: function(records, form){
			if(records && records.length > 0){
				Asg.Form.setValues(form, records[0].data);
			}
		},
		deleteDetails: function(grid, rowIndex, currentId) {
			var path = "/red/demandante/delete";
			switch(currentId){
				case "redFormacionDemandanteId":
					path += "eliminarRedDemandanteFormacionAcademica";
					break;
				case "redIdiomaDemandanteId":
					path += "eliminarRedDemandanteIdioma";
					break;
			}
			var rows = [grid.getStore().getAt(rowIndex)];
 		   	var currentIdAsLong = rows[0].get(currentId);
 		   	var redDemandanteFolio = Asg.Utils.getValue("redDemandanteFolio");
 		   	Asg.Message.progress("Actualizando Informaci\u00F3n...");
 		   	Ext.Ajax.request({
              timeout: Asg.constants.TIMEOUT_SECONDS,
              url: Asg.constants.CONTEXT_PATH + path,
              params: {redDemandanteFolio: redDemandanteFolio, currentId: currentIdAsLong},
              callback: function(options, success, response){
                  Ext.Msg.hide();
                  var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
                  if(!success || !jsonObject || jsonObject.failure){
                      Asg.Message.alertInvalid(Asg.constants.DEFAULT_ERROR_MESSAGE);
                      return
                  }
                  if(!Ext.isEmpty(jsonObject.message)) Asg.Message.alert(jsonObject.message);
                  if(jsonObject.list){
						Asg.Grid.loadData(grid.id, jsonObject.list);
					}
              }
 		   	});
		},
		resetFormDetails: function(form){
			form = Ext.getCmp(form);
			form.getForm().reset();
		},
		saveDetails: function(form, grid){
			if(Ext.isEmpty(Asg.Utils.getValue("redDemandanteFolio"))) {
				Asg.Message.alertInvalid("Debe Guardar al Demandante antes de continuar");
				return;
			}

			Asg.Message.alertInvalid(form);
			
			if(form=="redDemandanteIdiomaForm"){
				var idioma = Asg.Utils.getValue("redIdiomasDemandante.ctgIdioma.ctgCatalogoId");
				var idiomas = Ext.getCmp("redDemandanteIdiomaGrid").getStore().data;
				
				for (var i=0; i<idiomas.items.length; i++) {
	    		    var item = idiomas.items[i];	    		    
	    		    if(idioma == item.data["ctgIdiomaId"]){ 	    		    		
	    		    	Asg.Message.alert("Idioma duplicado!");
	         		    return;
	    		    }
	    		}				
			}
			
			if(form=="redDemandanteFormacionAcademica"){
				var escolaridad = Asg.Utils.getValue("redFormacionDemandante.ctgEscolaridad.ctgCatalogoId");
				var formacion_academica_grid = Ext.getCmp("redDemandanteFormacionAcademicaGrid").getStore().data;
				
				for (var i=0; i<formacion_academica_grid.items.length; i++) {
	    		    var item = formacion_academica_grid.items[i];	    		    
	    		    if(escolaridad == item.data["ctgEscolaridadId"]){ 	    		    		
	    		    	Asg.Message.alert("Escolaridad duplicada!");
	         		    return;
	    		    }
	    		}				
			}
			
			var path = "/red/demandante/";
			var params = {};
			var redDemandanteFolio = Asg.Utils.getValue("redDemandanteFolio");;
			switch(form){
				case "redDemandanteFormacionAcademica":
					path += "guardarRedDemandanteFormacionAcademica";
					params["redFormacionDemandante.redDemandante.redDemandanteFolio"] = redDemandanteFolio;
					break;
				case "redDemandanteIdiomaForm":
					path += "guardarRedDemandanteIdioma";
					params["redIdiomasDemandante.redDemandante.redDemandanteFolio"] = redDemandanteFolio;
					break;
				case "formPuestoBuscaExperiencia":
					path += "guardarRedPuestoDemandante";
					params["redPuestoBuscaDemandante.redDemandantes.redDemandanteFolio"] = redDemandanteFolio;
					break;
			}
			form = Ext.getCmp(form);
			Asg.Message.progress("Guardando Informaci\u00F3n...");
			form.getForm().submit({
    			url: Asg.constants.CONTEXT_PATH + path,
    			timeout: Asg.constants.TIMEOUT_SECONDS,
    			reset: true,
    			params: params,
    			success: function(form, action){
    				Asg.Message.alert(action.result.message);
					if(action.result.success){
						if(action.result.list){
							Asg.Grid.loadData(grid, action.result.list);
						}
					}
    			},
    			failure: Asg.Form.failureProcedure
   			});
		},
		navigate: function(panel, direction){
		    var layout = panel.getLayout();
		    var form = layout.getActiveItem();
		    var formId = form.getId();
		    var jsonParams = {};
		    if(formId == "redFormacionPaso" || formId == "formPuestoBuscaExperiencia"){
		    	RedDemandante.move(layout, direction);
		    	return;
		    }else{
		    	var path = "/red/demandante/";
		    	var params = {};
		    	switch(formId){
		    		case "formRegistroDemandante":
		    			path += "validateDocument";
		    			params["ctgDocumentoId"] = Asg.Utils.getValue("ctgDocumentoId");
			    		params["redDemandanteNumeroDocumento"] = Asg.Utils.getValue("redDemandanteNumeroDocumento");
		    			break;
		    		case "formDatosPersonalesDemandante":
		    			path += "guardarDemandante";
		    			params["redDemandante.redDemandanteFolio"] = Asg.Utils.getValue("redDemandanteFolio");
			    		params["redDemandante.ctgDocumento.ctgDocumentoId"] = Asg.Utils.getValue("ctgDocumentoId");
			    		params["redDemandante.sgdUsuario.sgdUsuarioId"] = Asg.Utils.getValue("sgdUsuario");
			    		params["redDemandante.ctgOficina.ctgOficinaId"] = Asg.Utils.getValue("ctgOficina");
			    		params["redDemandante.redDemandanteNumeroDocumento"] = Asg.Utils.getValue("redDemandanteNumeroDocumento");
			    		params["redDemandante.redDemandanteFechaRegistro"] = Asg.Utils.getValue("redDemandanteFechaRegistro");
		    			break;
		    		case "formDisposicionDemandante":
			    		path += "guardarDisposicionDemandante";
			    		params["redDemandanteFolio"] = Asg.Utils.getValue("redDemandanteFolio");
			    		params["ctgJornadaId"] = Asg.Utils.getValue("ctgJornada");
			    		params["ctgTipoContratoId"] = Asg.Utils.getValue("ctgTipoContrato");
			    		break;
		    		case "formPestoBuscaExperiencia":
		    			path += "guardarPuestoExperienciaDemandante";
		    			break;
		    		case "formMonitoreoBusqueda":
			    		path += "guardarMonitoreoDemandante";
			    		params["redDemandanteFolio"] = Asg.Utils.getValue("redDemandanteFolio");
			    		break;
		    	}
		    }
		    Asg.Message.progress("Guardando Informaci\u00F3n...");
		    form.getForm().submit({
    			url: Asg.constants.CONTEXT_PATH + path,
    			timeout: Asg.constants.TIMEOUT_SECONDS,
    			params: params,
    			success: function(form, action){
    				Asg.Message.alert(action.result.message);
					if(action.result.success){
						if(action.result.redDemandanteFolio) Asg.Utils.setValue("redDemandanteFolio", action.result.redDemandanteFolio);
						if(action.result.redDemandanteFechaRegistro) Asg.Utils.setValue("redDemandanteFechaRegistro", action.result.redDemandanteFechaRegistro);
						RedDemandante.move(layout, direction);
					}
    			},
    			failure: Asg.Form.failureProcedure
   			});
		},
		move: function(layout, direction){
			layout[direction]();
			Ext.getCmp("btnValidate").setDisabled(!layout.getPrev());
		    Ext.getCmp("btnBack").setDisabled(!layout.getNext());
		},
		openWindow: function(redDemandanteFolio){
			Asg.Message.progress("Cargando Informaci\u00F3n...");
            Ext.Ajax.request({
            	 timeout: Asg.constants.TIMEOUT_SECONDS,
            	 url: Asg.constants.CONTEXT_PATH + "/red/demandante/findById",
                 params: {redDemandanteFolio: redDemandanteFolio},
                 callback: function(options, success, response){
                     Ext.Msg.hide();
                     var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
                     if(!success || !jsonObject || jsonObject.failure){
                         Asg.Message.alertInvalid(Asg.constants.DEFAULT_ERROR_MESSAGE);
                         return
                     }
                     RedDemandante.registroWindow(jsonObject);
                 }
            });
		},
		registroWindow: function(config){
			if(!config) config = {};
			if(!config.demandante) config.demandante = {};
			index = 0;
			new Ext.Window({
				id: "registroWindow",
				layout: "fit", 
				title: Asg.constants.APPLICATION_TITLE + " .::. ASISTENTE DE DEMANDANTE",
				modal: true,
				width: 850,
				height: 600,
				maximizable: true,
				resizable	: true,
	        	bodyStyle: "background: #DFE8F6",
	        	items: {
	    			layout: "card",
	    			border: false,
	    			id: "asistenteDemandante",
	    			frame: true,
	    			activeItem: RedDemandante.index,
	    			items: [
	    			    RedDemandantesForms.seccionControlDemandante(config),
	    			    RedDemandantesForms.datosPersonalesDemandante(config),
	    			    RedDemandantesForms.formacionAcademicaDemandante(config),
	    			    RedDemandantesForms.formacionPuestoyExpriencia(config),
	    			    RedDemandantesForms.condicionesIncorporacion(config),
	    			    RedDemandantesForms.monitoreoBusqueda(config)
	    			    		
	     		    ],
	    		 bbar: [
     		            "->",
 		               {
 		            	   text: "Anterior",
 		            	   id: "btnBack",
 		            	   handler: function(btn) {
 		            		  RedDemandante.navigate(btn.up("panel"), "prev");
 		                   },
 		                   disabled: true
 		               },"-",
 		               {
 		            	   text: "Siguiente",
 		            	   id: "btnValidate",
 		            	   handler: function(btn) {
 		            		  RedDemandante.navigate(btn.up("panel"), "next");
 		                   }
 		               }, "-",
 		               {
 		            	   text: "Cerrar",
 		            	   handler: function(){
 		            		   Ext.WindowMgr.get("registroWindow").close();
 	            		   }
 		               }
	  	    		]
	        	}
			}).show();
		},
		initConfig: function(config){
			config = config || {};
			Ext.define("redDemandanteModel",{
				extend: "Ext.data.Model",
				fields:[
			        "reddemandantefolio","reddemandantefullname","reddemandantenit","reddemandantedui"
			    ]
			});
			var redDemandanteStore = Ext.create("Ext.data.Store", {
				model: "redDemandanteModel",
				proxy: {
			        type: "ajax",
			        url: Asg.Utils.formatString("{0}/red/demandante/buscarDemandantes", Asg.constants.CONTEXT_PATH),
			        reader: {
			        	type: "json",
			        	root: "demandante"
	        		}
			    },
			    listeners: {
			    	beforeload: function(store, operation, options){
			    		if(!operation) operation = {};
			    		if(!operation.params) operation.params = {};
			    		if(Asg.Utils.getValue("opcion"))
			    			operation.params["opcion"] = Asg.Utils.getValue("opcion");
			    		if(Asg.Utils.getValue("estado"))
			    			operation.params["estado"] = Asg.Utils.getValue("estado");
			    		if(Asg.Utils.getValue("nombreDemandante"))
			    			operation.params["nombreDemandante"] = Asg.Utils.getValue("nombreDemandante");
			    	}
			    }
			});
			return {
				items: {
					xtype: 'grid',
					id: 'gridDemandantes',					
					flex: 1,
					margins: "5 5 5 5",
					store: redDemandanteStore,
					title: 'CONSULTA DE DEMANDANTES',
					columns: [
				          {
				        	xtype:"actioncolumn",
				        	width: 165,				        	
		        			items: [
	        			        {
	        			        	icon: Asg.constants.CONTEXT_PATH + "/resources/images/edit.png",
	        			        	tooltip: "EDITAR DEAMANDANTE",
	        			        	iconCls: "action_icons",
	        			        	handler: function(grid, rowIndex, colIndex){
	        			        		var record = grid.getStore().getAt(rowIndex);
	        			        		if(record != null){
	        			        			RedDemandante.openWindow(record.get("reddemandantefolio"));
	        			        		}
	        			        	}
	        			        }, {
	        			        	icon: Asg.constants.CONTEXT_PATH + "/resources/images/page_pdf.png",
	        			        	tooltip: "VER FICHA",
	        			        	iconCls: "action_icons",
	        			        	handler: function(grid, rowIndex, colIndex) {
	        			        		/*	 var records = Ext.getCmp("redDemandantesByOfertaGrid").getStore().queryBy(function(record) {
					         			return record.get('seleccionado') === true;
					         		});
					         		var ids = [];
					         		records.each(function(record) {
					         			ids.push(record.get('reddemandantefolio'));
					         		});*/
					        		 var rows = [grid.getStore().getAt(rowIndex)];
					        		 var folio = rows[0].get("reddemandantefolio");
					        		 var urlServer = "/pentaho/content/reporting/reportviewer/report.html?solution=CubosMTPS&path=%2FReportes&name=hojadevida.prpt#Folio="+folio+"&userid=reportes&password=reportes&output-target=pageable%252Fpdf&showParameters=false&solution=CubosMTPS&path=%252FReportes&name=hojadevida.prpt";
					        		 window.open("http://192.168.1.20:8181"+urlServer,"HojaVida","resizable=yes,scrollbars=yes,status=yes");
					         		//alert("imprimiendo carta"+ rows[0].get("reddemandantefolio"));
								     	 }
	        			        },{
	        			        	icon: Asg.constants.CONTEXT_PATH + "/resources/images/find.png",
	        			        	tooltip: "BUSCAR OFERTA",
	        			        	iconCls: "action_icons",
	        			        	handler: function(grid, rowIndex, colIndex){
	        			        		var record = grid.getStore().getAt(rowIndex);
	        			        		if(record != null){
	        			        			RedVincularDemandante.windowRedVincularDemandante(record.get("reddemandantefolio"));
	        			        		}
	        			        	}
	        			        },{
	        			        	icon: Asg.constants.CONTEXT_PATH + "/resources/images/user_go.png",
	        			        	tooltip: "AFECTAR DEMANDANTE",
	        			        	iconCls: "action_icons",
	        			        	handler: function(grid, rowIndex, colIndex){
	        			        		var record = grid.getStore().getAt(rowIndex);
	        			        		if(record != null){
	        			        			RedAfectarDemandante.windowAfectarDemandante(record.get("reddemandantefullname"),record.get("reddemandantefolio"));
	        			        		}
	        			        	}
	        			        },//,{
//	        			        	icon: Asg.constants.CONTEXT_PATH + "/resources/images/verification.png",
//	        			        	tooltip: "ACTIVAR / INACTIVAR",
//	        			        	iconCls: "action_icons",
//	        			        	handler: function(grid, rowIndex, colIndex){
//	        			        		var record = grid.getStore().getAt(rowIndex);
//	        			        		if(record != null){
//	        			        			RedActivacionDemandante.windowActivacionDemandante(record.get("reddemandantefolio"));
//	        			        		}
//	        			        	}
	        			        //},
	        			        {
	        			        	icon: Asg.constants.CONTEXT_PATH + "/resources/images/comments.png",
	        			        	tooltip: "OBSERVACIONES",
	        			        	iconCls: "action_icons",
	        			        	handler: function(grid, rowIndex, colIndex){
	        			        		var record = grid.getStore().getAt(rowIndex);
	        			        		if(record != null){
	        			        			RedObservaciones.bitacoraObservaciones(record.get("reddemandantefullname"),record.get("reddemandantefolio"));
	        			        		}
	        			        		
	        			        	}
	        			        },{
	        			        	icon: Asg.constants.CONTEXT_PATH + "/resources/images/discap.gif",
	        			        	tooltip: "PERFIL DE DISCAPACIDAD",
	        			        	iconCls: "action_icons",
	        			        	handler: function(grid, rowIndex, colIndex) {
     	        	        		   var rows = [grid.getStore().getAt(rowIndex)];
     	        	        		   RedDiscapacidad.openWindow(rows[0].get("reddemandantefolio"));
     	        	        	   }
	        			        },{
	        			        	icon: Asg.constants.CONTEXT_PATH + "/resources/images/historialImg.gif",
	        			        	tooltip: "BITACORA OFERTAS",
	        			        	iconCls: "action_icons",
	        			        	handler: function(grid, rowIndex, colIndex) {
     	        	        		   var rows = [grid.getStore().getAt(rowIndex)];
     	        	        		   RedBitacoraOfertaDemandante.windowBitacoraOfertaDemandante(rows[0].get("reddemandantefolio"));
     	        	        	   }
	        			        }
	    			        ]
				          },
				          {header: 'Nombres', dataIndex: 'reddemandantefullname',flex:1},
					],
					tbar: [
	        	       "->",
	        	       {
	        	    	   text: "Agregar Demandante", 
	        	    	   iconCls: Asg.constants.ADD_ICON,
	        	    	   handler: function(){
	        	    		   RedDemandante.openWindow();
	        	    	   }
        	    	   },
        	    	   {
	           	        	text: "Buscar",
	           	        	iconCls: Asg.constants.BUSCAR_ICON,
	           	        	handler: function(){
	           	        		var store = Ext.getCmp("gridDemandantes").getStore();
	           	        		console.log(Ext.getCmp("estado").value);
	           	        		//Agregado por Hugo GOnzalez EDC para ocultar iconos dependiendo si esta activo o no
	           	        		if(Ext.getCmp("estado").value==0){
	           	        			Ext.getCmp("gridDemandantes").columns[0].items[3].iconCls = "x-hide-display";
	           	        		}else{
	           	        			Ext.getCmp("gridDemandantes").columns[0].items[3].iconCls = "action_icons";	           	        			
	           	        		}
	           	        		//Ext.getCmp("gridDemandantes").columns[0].items[0] = null;
		           	 			store.currentPage = 1;
		           	 			store.load();
	           	        	}
	           	        }
        	        ],
        	        dockedItems: [{
        	        	xtype: "toolbar",
		            	dock: "top",
		            	items: [
	            	       "<b>DEMANDANTES</b>",
	            	       {
	            	    	    xtype: "combobox",
		        	        	name: "opcion",
		        	        	id: "opcion",
		        	        	width: 205,
		        	        	labelWidth: 175,
		        	        	margins: "0 0 0 6", 
		        	        	value: 1,
								afterLabelTextTpl:  Asg.constants.REQUIRED,
								allowBlank:false,
								store: new Ext.data.SimpleStore({
									data: [[1,"Mis Demandantes"],[2,"Demandantes de di Oficina"],[3,"Todas"]] , 
									fields: ["id","value"]
								}),
								valueField: "id",
								displayField: "value"
	            	       },
	            	       "<b>ESTADO</b>",
	            	       {
	            	    	   	xtype: "combobox",
		        	        	name: "estado",
		        	        	id: "estado",
		        	        	width: 205,
		        	        	margins: "0 0 0 6", 
		        	        	value: "1",
								afterLabelTextTpl:  Asg.constants.REQUIRED,
								allowBlank:false,
								store: new Ext.data.SimpleStore({
									data: [["1","ACTIVAS"],["0","INACTIVAS"]] , 
									fields: ["id","value"]
								}),
								valueField: "id",
								displayField: "value"
	            	       },
	            	       "<b>NOMBRE</b>",
	            	       {
	            	    	   xtype: "textfield",
	            	    	   name: "nombreDemandante",
	            	    	   id: "nombreDemandante",
	            	    	   margins: "0 0 0 6",
	            	    	//   labelWidth: 255,
	            	    	   emptyText: "Ingrese criterio",
	            	    	   width: 225
	            	    	 //  anchor: "100%"
	            	       }
		            	]
        	        }]
				}
			};
		}
	};
}();